import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import { ElMessage } from 'element-plus';
import JsBarcode from 'jsbarcode';

/**
 * 画布初始化和操作相关函数
 * @param {Object} options 配置选项
 * @returns {Object} 返回画布操作函数
 */
export default function useCanvas(options = {}) {
  const {
    initialWidth = 148,
    initialHeight = 105,
    initialPxPerMm = 3.78,
    canvasId = 'designer-canvas',
    onObjectSelected = () => { },
    onSelectionCleared = () => { },
    onObjectModified = () => { },
    onContentChanged = () => { },
  } = options;

  // 添加辅助线相关状态
  const guideLines = ref({
    horizontal: null,
    vertical: null,
    horizontalBottom: null, // 添加底部水平辅助线
    verticalRight: null,    // 添加右侧垂直辅助线
    info: null
  });

  // 确保window对象存在并初始化全局canvas变量
  if (typeof window !== 'undefined') {
    // 如果window.globalCanvas不存在，则初始化为null
    if (window.globalCanvas === undefined) {
      window.globalCanvas = null;
    }
  }
  // 保留一个响应式引用用于触发UI更新
  const canvasRef = ref(null);
  const selectedObject = ref(null);
  const canvasContentWidth = ref(initialWidth);
  const canvasContentHeight = ref(initialHeight);
  const saved = ref(true);

  // 初始化时创建响应式的比例变量
  const pxPerMm = ref(initialPxPerMm || 3.78);

  // 初始化画布
  const initCanvas = (width, height) => {
    console.log('开始初始化画布...');

    try {
      const canvasWidth = mmToPx(width || initialWidth);
      const canvasHeight = mmToPx(height || initialHeight);

      // 检查并销毁现有的Canvas实例
      if (window.globalCanvas) {
        console.log('清理现有Canvas实例...');
        try {
          // 删除所有事件监听器
          window.globalCanvas.off();
          // 销毁实例
          window.globalCanvas.dispose();
          window.globalCanvas = null;

          // 检查并移除多余的canvas元素
          const extraCanvases = document.querySelectorAll('.upper-canvas');
          if (extraCanvases.length > 1) {
            console.log(`检测到${extraCanvases.length}个upper-canvas元素，清理多余画布...`);
            extraCanvases.forEach((canvas, index) => {
              if (index > 0) {
                canvas.parentNode.removeChild(canvas);
              }
            });
          }
        } catch (error) {
          console.error('清理Canvas实例时出错:', error);
        }
      }

      // 配置全局Fabric设置
      configureFabric();

      // 尝试获取canvas元素
      const canvasElement = document.getElementById(canvasId);
      if (!canvasElement) {
        console.error(`找不到canvas元素，ID: ${canvasId}`);
        return;
      }

      console.log(`找到canvas元素，ID: ${canvasId}，初始化fabric.Canvas...`);

      // 创建fabric.Canvas实例
      window.globalCanvas = new window.fabric.Canvas(canvasId, {
        width: canvasWidth,
        height: canvasHeight,
        backgroundColor: '#ffffff',
        selection: true
      });

      if (!window.globalCanvas) {
        console.error('fabric.Canvas初始化失败');
        return;
      }

      console.log('fabric.Canvas初始化成功，设置画布事件...');



      // 设置事件处理
      setupCanvasEvents();

      // 调整Canvas容器样式
      updateCanvasStyles();

      console.log(`画布初始化完成，尺寸: ${canvasWidth}x${canvasHeight}，缩放比例: ${pxPerMm.value}px/mm`);
    } catch (error) {
      console.error('初始化画布时出错:', error);
    }
  };

  // 配置Fabric.js全局设置
  const configureFabric = () => {
    // 确保Fabric已加载
    if (!window.fabric) {
      console.warn('Fabric.js未加载');
      return;
    }

    // 配置Textbox类
    const Textbox = window.fabric.Textbox;
    if (Textbox) {
      // 修改默认文本编辑行为
      Textbox.prototype._keysMap = {
        ...Textbox.prototype._keysMap,
        'ctrl+a': 'selectAll'
      };

      // 为Textbox添加换行按钮功能
      Textbox.prototype.addNewlineButton = function () {
        // 如果已经添加过按钮，则不重复添加
        if (this._newlineButtonAdded) return;

        // 创建换行按钮元素
        const newlineBtn = document.createElement('button');
        newlineBtn.textContent = '换行';
        newlineBtn.className = 'fabric-newline-btn';
        newlineBtn.style.position = 'absolute';
        newlineBtn.style.zIndex = '999';
        newlineBtn.style.backgroundColor = '#5E9ED6';
        newlineBtn.style.color = 'white';
        newlineBtn.style.border = 'none';
        newlineBtn.style.borderRadius = '3px';
        newlineBtn.style.padding = '4px 8px';
        newlineBtn.style.fontSize = '12px';
        newlineBtn.style.cursor = 'pointer';
        newlineBtn.style.display = 'none'; // 初始隐藏

        // 将按钮添加到画布容器中
        const canvasContainer = this.canvas.wrapperEl;
        canvasContainer.appendChild(newlineBtn);

        // 保存按钮引用
        this._newlineButton = newlineBtn;
        this._newlineButtonAdded = true;

        // 为按钮添加点击事件
        newlineBtn.addEventListener('click', () => {
          // 检查是否处于编辑状态
          if (!this.isEditing) return;

          // 在Fabric中实现换行的正确方法
          this.insertChars('\n', null, this.selectionStart + 1);
          this.canvas.renderAll();
          console.log('已在文本中插入换行');
        });

        // 监听编辑状态变化
        this.on('editing:entered', () => {
          // 显示换行按钮
          this.updateNewlineButtonPosition();
          this._newlineButton.style.display = 'block';
        });

        this.on('editing:exited', () => {
          // 隐藏换行按钮
          this._newlineButton.style.display = 'none';
        });

        this.on('moving', () => {
          if (this.isEditing) {
            this.updateNewlineButtonPosition();
          }
        });

        // 监听画布缩放事件
        this.canvas.on('mouse:wheel', () => {
          if (this.isEditing) {
            this.updateNewlineButtonPosition();
          }
        });
      };

      // 更新换行按钮位置的方法
      Textbox.prototype.updateNewlineButtonPosition = function () {
        if (!this._newlineButton || !this.canvas) return;

        // 获取对象的绝对坐标
        const objCoords = this.getCoords();
        // 使用右上角坐标
        const point = objCoords[1]; // 右上角坐标

        // 计算按钮位置
        const zoom = this.canvas.getZoom();
        const pan = this.canvas.viewportTransform;

        // 应用缩放和平移转换
        const btnLeft = point.x * zoom + pan[4];
        const btnTop = point.y * zoom + pan[5];

        // 设置按钮位置
        this._newlineButton.style.left = `${btnLeft + 10}px`; // 右上角右侧10px处
        this._newlineButton.style.top = `${btnTop - 30}px`; // 右上角上方30px处
      };

      // 扩展默认键盘处理，支持Shift+Enter插入换行
      const originalHandleKeyDown = Textbox.prototype._handleKeyDown;
      Textbox.prototype._handleKeyDown = function (e) {
        // 如果按下Shift+Enter，插入换行符
        if (e.key === 'Enter' && e.shiftKey) {
          e.preventDefault();

          // 使用Fabric的标准方法插入换行符
          this.insertChars('\n', null, this.selectionStart + 1);
          this.canvas.renderAll();

          return;
        }

        // 对于其他键盘事件，调用原始处理方法
        return originalHandleKeyDown.call(this, e);
      };

      // 扩展enterEditing方法添加换行按钮
      const originalEnterEditing = Textbox.prototype.enterEditing;
      Textbox.prototype.enterEditing = function (e) {
        const result = originalEnterEditing.call(this, e);

        // 确保换行按钮已添加并正确显示
        if (!this._newlineButtonAdded) {
          this.addNewlineButton();
        }

        if (this._newlineButton) {
          this.updateNewlineButtonPosition();
          this._newlineButton.style.display = 'block';
        }

        return result;
      };

      // 扩展exitEditing方法隐藏换行按钮
      const originalExitEditing = Textbox.prototype.exitEditing;
      Textbox.prototype.exitEditing = function () {
        if (this._newlineButton) {
          this._newlineButton.style.display = 'none';
        }

        return originalExitEditing.call(this);
      };

      // 扩展初始化方法确保每个文本对象都具有换行按钮功能
      const originalInitialize = Textbox.prototype.initialize;
      Textbox.prototype.initialize = function () {
        const result = originalInitialize.apply(this, arguments);

        // 设置一个定时器，等待对象完全初始化后再添加按钮
        setTimeout(() => {
          if (this.canvas) {
            this.addNewlineButton();
          }
        }, 0);

        return result;
      };

      // 重写双击事件处理
      Textbox.prototype._onDoubleClick = function (options) {
        if (!this.editable) return;

        // 计算点击位置对应的字符索引
        const canvas = this.canvas;
        const pointer = canvas.getPointer(options.e);
        const clickPoint = this.toLocalPoint(new window.fabric.Point(pointer.x, pointer.y), 'left', 'top');

        if (!this.isEditing) {
          this.enterEditing(options.e);
        }

        // 计算点击位置对应的字符索引
        const charIndex = this.getSelectionStartFromPointer(clickPoint.x, clickPoint.y);

        // 设置光标位置
        this.setSelectionStart(charIndex);
        this.setSelectionEnd(charIndex);
        this.initDimensions();
        this.hiddenTextarea.selectionStart = charIndex;
        this.hiddenTextarea.selectionEnd = charIndex;

        // 强制更新光标位置
        this._updateTextarea();
        this.canvas.renderAll();
      };

      // 扩展Textbox原型以添加鼠标事件处理
      Textbox.prototype.initMousedownHandler = function () {
        // 确保该方法只被初始化一次
        if (this._mousedownHandlerInitialized) return;

        // 标记该方法已被初始化
        this._mousedownHandlerInitialized = true;

        // 添加鼠标按下事件处理器
        this.on('mousedown', function (options) {
          try {
            // 安全检查：确保canvas存在
            if (!this.canvas) {
              console.warn('Textbox mousedown: canvas 不存在');
              return;
            }

            // 安全检查：确保必要的方法存在
            if (typeof this.toLocalPoint !== 'function' || typeof this.canvas.getPointer !== 'function') {
              console.warn('Textbox mousedown: 必要的方法不存在', {
                hasToLocalPoint: typeof this.toLocalPoint === 'function',
                hasGetPointer: typeof this.canvas.getPointer === 'function'
              });
              return;
            }

            // 获取点击点的坐标
            const pointer = this.canvas.getPointer(options.e);

            // 计算点击点相对于文本对象的本地坐标
            const localPoint = this.toLocalPoint(pointer, 'center', 'center');

            // 保存点击位置用于编辑模式下的光标放置
            this._lastClickPosition = localPoint;

            // 如果当前处于编辑模式，则设置光标位置
            if (this.isEditing) {
              const charIndex = this.getSelectionStartFromPointer(options.e);
              this.selectionStart = charIndex;
              this.selectionEnd = charIndex;
              this.initDelayedCursor(true);
            }
          } catch (error) {
            console.error('Textbox mousedown 处理器错误:', error);
          }
        });
      };

      // 添加自定义高度功能

      // 应用自定义高度
      Textbox.prototype._applyCustomHeight = function () {
        if (this.customHeight !== undefined) {
          // 先记住原始计算高度
          if (!this._calcedHeight) {
            this._calcedHeight = this.height;
          }
          // 设置自定义高度
          this.height = this.customHeight;
        }
        return this;
      };

      // 覆写尺寸初始化方法
      const originalInitDimensions = Textbox.prototype._initDimensions;
      Textbox.prototype._initDimensions = function (ctx) {
        // 调用原始方法计算基本尺寸
        originalInitDimensions.call(this, ctx);

        // 应用自定义高度
        this._applyCustomHeight();
        return this;
      };

      // 设置自定义高度的方法
      Textbox.prototype.setCustomHeight = function (height) {
        this.customHeight = height;

        // 如果已在画布上，立即应用
        if (this.canvas) {
          this.dirty = true;
          this.initDimensions(this.canvas.getContext('2d'));
          this.setCoords();
          this.canvas.renderAll();
        }

        return this;
      };

      // 覆写缩放方法
      const originalScale = Textbox.prototype.scale;
      Textbox.prototype.scale = function (scaleX, scaleY) {
        // 保存当前高度
        const currentHeight = this.height;

        // 调用父类缩放
        originalScale.call(this, scaleX, scaleY);

        // 应用宽度缩放
        if (scaleX !== 1) {
          this.width = this.width * scaleX;
          this.scaleX = 1;
        }

        // 应用高度缩放
        if (scaleY !== 1) {
          this.customHeight = currentHeight * scaleY;
          this.height = this.customHeight;
          this.scaleY = 1;
        }

        // 确保字体大小不变
        if (this._initialFontSize) {
          this.set('fontSize', this._initialFontSize);
        }

        return this;
      };

      // 重写 _applyScale 方法来确保高度能够正确缩放
      Textbox.prototype._applyScale = function () {
        if (this._scaling) return;

        this._scaling = true;

        // 保存当前宽高比
        const currentWidth = this.width * this.scaleX;
        const currentHeight = this.height * this.scaleY;

        // 重设宽度
        if (this.scaleX !== 1) {
          this.width = currentWidth;
          this.set('scaleX', 1);
        }

        // 重设高度，确保不会自动缩回
        if (this.scaleY !== 1) {
          this.customHeight = currentHeight;
          this.set('height', currentHeight);
          this.set('scaleY', 1);
        }

        // 确保字体大小保持不变
        if (this._initialFontSize) {
          this.set('fontSize', this._initialFontSize);
        }

        this._scaling = false;

        if (this.canvas) {
          this.canvas.renderAll();
        }
      };

      // 覆写属性设置方法
      const originalSet = Textbox.prototype._set;
      Textbox.prototype._set = function (key, value) {
        // 如果设置高度且不是在缩放过程中
        if (key === 'height' && this.customHeight !== undefined && !this._scaling) {
          this.customHeight = value;
        }

        // 如果设置字体大小且没有初始值
        if (key === 'fontSize' && this._initialFontSize === undefined) {
          this._initialFontSize = value;
        }

        // 调用原始方法
        return originalSet.call(this, key, value);
      };

      // 确保边框能跟随自定义高度变化
      Textbox.prototype.setBorder = function (options = {}) {
        // 设置边框属性
        this.set({
          textboxBorderColor: options.color || '#000000',
          textboxBorderWidth: options.width || 1,
          textboxBorderDash: options.dashArray || null,
          textboxBorderVisible: options.show !== false,
          textboxPadding: options.padding !== undefined ? options.padding : 5, // 默认5像素的内边距
          // 添加边框方向控制
          textboxBorderTop: options.top === true,
          textboxBorderRight: options.right === true,
          textboxBorderBottom: options.bottom === true,
          textboxBorderLeft: options.left === true
        });

        // 直接强制刷新
        if (this.canvas) {
          this.canvas.requestRenderAll();
        }

        return this;
      };

      // 扩展渲染方法，确保边框正确渲染
      const originalRender = Textbox.prototype._render;
      Textbox.prototype._render = function (ctx) {
        // 先调用原始渲染方法渲染文本
        originalRender.call(this, ctx);

        // 如果设置了边框属性，则单独渲染边框
        if (this.textboxBorderVisible && this.textboxBorderWidth > 0) {
          // 获取内边距，默认为5像素
          const padding = this.textboxPadding !== undefined ? this.textboxPadding : 5;

          // 计算带内边距的边框尺寸
          const w = this.width + padding * 2;
          const h = this.height + padding * 2;
          const x = -this.width / 2 - padding;
          const y = -this.height / 2 - padding;

          ctx.save();

          // 设置边框样式
          ctx.lineWidth = this.textboxBorderWidth;
          ctx.strokeStyle = this.textboxBorderColor;

          // 设置虚线样式（如果有）
          if (this.textboxBorderDash && this.textboxBorderDash.length > 0) {
            ctx.setLineDash(this.textboxBorderDash);
          }

          // 绘制边框 - 分别控制上、右、下、左四个边框
          if (this.textboxBorderTop) {
            ctx.beginPath();
            ctx.moveTo(x, y);
            ctx.lineTo(x + w, y);
            ctx.stroke();
          }

          if (this.textboxBorderRight) {
            ctx.beginPath();
            ctx.moveTo(x + w, y);
            ctx.lineTo(x + w, y + h);
            ctx.stroke();
          }

          if (this.textboxBorderBottom) {
            ctx.beginPath();
            ctx.moveTo(x + w, y + h);
            ctx.lineTo(x, y + h);
            ctx.stroke();
          }

          if (this.textboxBorderLeft) {
            ctx.beginPath();
            ctx.moveTo(x, y + h);
            ctx.lineTo(x, y);
            ctx.stroke();
          }

          ctx.restore();
        }
      };

      // 覆写toObject方法，确保自定义属性被序列化
      const originalToObject = Textbox.prototype.toObject;
      Textbox.prototype.toObject = function (propertiesToInclude) {
        return originalToObject.call(this, [
          'customHeight',
          'textboxBorderColor',
          'textboxBorderWidth',
          'textboxBorderDash',
          'textboxBorderVisible',
          'textboxPadding',
          'textboxBorderTop',
          'textboxBorderRight',
          'textboxBorderBottom',
          'textboxBorderLeft',
          '_initialFontSize',
          ...(propertiesToInclude || [])
        ]);
      };
    }

    // 增强控制点行为，提高拉伸精度
    window.fabric.Object.prototype.cornerSize = 8; // 增大控制点尺寸
    window.fabric.Object.prototype.transparentCorners = false; // 不透明控制点
    window.fabric.Object.prototype.cornerColor = '#5E9ED6'; // 控制点颜色
    window.fabric.Object.prototype.borderColor = '#5E9ED6'; // 边框颜色
    window.fabric.Object.prototype.cornerStrokeColor = '#FFFFFF'; // 控制点边框颜色

    fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'left';
    fabric.Text.prototype.snapToPixel = true;
    // 修改控制点的触摸区域，提高拉伸精度
    window.fabric.Object.prototype.touchCornerSize = 24; // 增大触摸区域
    window.fabric.Object.prototype.borderScaleFactor = 2; // 增大边框缩放因子

    // 设置对象的控制点属性，使拉伸更容易
    const originalInitControls = window.fabric.Object.prototype._initControls;
    window.fabric.Object.prototype._initControls = function () {
      originalInitControls.call(this);

      // 增强控制点的拉伸灵敏度
      if (this.controls) {
        // 增强四角控制点
        ['tl', 'tr', 'bl', 'br'].forEach(corner => {
          if (this.controls[corner]) {
            this.controls[corner].touchSizeX = 1.5;
            this.controls[corner].touchSizeY = 1.5;
            this.controls[corner].sizeX = 1.2;
            this.controls[corner].sizeY = 1.2;
          }
        });

        // 增强边缘控制点
        ['mt', 'mb', 'ml', 'mr'].forEach(corner => {
          if (this.controls[corner]) {
            this.controls[corner].touchSizeX = 1.5;
            this.controls[corner].touchSizeY = 1.5;
            this.controls[corner].sizeX = 1.2;
            this.controls[corner].sizeY = 1.2;
          }
        });
      }
    };
  };

  // 设置画布事件
  const setupCanvasEvents = () => {
    if (!window.globalCanvas) return;

    // 清除已有的监听器，避免重复绑定
    window.globalCanvas.off('object:selected');
    window.globalCanvas.off('selection:created');
    window.globalCanvas.off('selection:cleared');
    window.globalCanvas.off('object:modified');
    window.globalCanvas.off('object:scaling');
    window.globalCanvas.off('object:removed');
    window.globalCanvas.off('mouse:dblclick');

    // 监听对象选中事件
    window.globalCanvas.on('object:selected', handleObjectSelected);
    window.globalCanvas.on('selection:created', handleObjectSelected);

    // 监听选择清除事件
    window.globalCanvas.on('selection:cleared', () => {
      selectedObject.value = null;
      onSelectionCleared();
    });

    // 监听对象修改事件
    window.globalCanvas.on('object:modified', (e) => {
      const modifiedObj = e.target;
      selectedObject.value = modifiedObj;
      onObjectModified(modifiedObj);

      // 标记为未保存状态
      saved.value = false;

      // 调用内容变更回调
      onContentChanged();
    });


    // 监听对象缩放事件
    // window.globalCanvas.on('object:scaling', handleObjectScaling);

    // 监听对象删除事件 - 重要改进点
    window.globalCanvas.on('object:removed', (e) => {
      const removedObj = e.target;
      console.log('对象被删除事件触发:', removedObj);

      // 确保移除的对象有完整的信息
      if (removedObj) {
        // 创建一个完整的对象信息记录，以便外部处理
        const removedObjInfo = {
          customType: removedObj.customType || '',
          fieldName: removedObj.fieldName || '',
          fieldType: removedObj.fieldType || '',
          id: removedObj.id || Date.now().toString(),
          type: removedObj.type || '',
          // 添加额外信息以方便调试
          isCustomField: removedObj.customType === 'field'
        };

        console.log('传递被删除对象信息到外部处理函数:', removedObjInfo);

        // 调用外部提供的回调（如果存在）
        if (typeof options.onObjectRemoved === 'function') {
          try {
            options.onObjectRemoved(removedObjInfo);
            console.log('成功调用外部对象删除处理函数');
          } catch (error) {
            console.error('调用外部对象删除处理函数时出错:', error);
          }
        } else {
          console.warn('未提供对象删除处理回调函数 onObjectRemoved');
        }
      }
    });

    // 监听双击事件
    window.globalCanvas.on('mouse:dblclick', handleDoubleClick);

    console.log('画布事件监听器已设置');

    // 初始化辅助线
    initGuideLines();
    
    // 添加对象移动事件处理
    window.globalCanvas.on('object:moving', (e) => {
      if (!guideLines.value.horizontal || !guideLines.value.vertical) return;
      
      const obj = e.target;
      if (!obj) return;
      
      // 获取对象的位置和尺寸信息
      const objLeft = obj.left;
      const objTop = obj.top;
      const objWidth = obj.width * (obj.scaleX || 1);
      const objHeight = obj.height * (obj.scaleY || 1);
      // 计算对象的右边和底部坐标
      const objRight = objLeft + objWidth;
      const objBottom = objTop + objHeight;
      
      // 调整辅助线位置 - 考虑到刻度尺的位置(30px)
      const rulerOffset = 30;
      

      if(obj.customType !== 'verticalLine'){
        // 显示左侧垂直辅助线
        guideLines.value.vertical.style.display = 'block';
        guideLines.value.vertical.style.left = `${objLeft + rulerOffset}px`;

        // 显示上方水平辅助线
        guideLines.value.horizontal.style.display = 'block';
        guideLines.value.horizontal.style.top = `${objTop + rulerOffset}px`;

        // 显示右侧垂直辅助线
        if (guideLines.value.verticalRight) {
          guideLines.value.verticalRight.style.display = 'block';
          guideLines.value.verticalRight.style.left = `${objRight + rulerOffset}px`;
        }

        // 显示底部水平辅助线
        if (guideLines.value.horizontalBottom) {
          guideLines.value.horizontalBottom.style.display = 'block';
          guideLines.value.horizontalBottom.style.top = `${objBottom + rulerOffset}px`;
        }
      }else {
         // 显示左侧垂直辅助线
         guideLines.value.vertical.style.display = 'block';
         guideLines.value.vertical.style.left = `${objLeft + rulerOffset}px`;
 
         // 显示上方水平辅助线
         guideLines.value.horizontal.style.display = 'block';
         guideLines.value.horizontal.style.top = `${objTop + rulerOffset-(obj.y2/2)}px`;

         // 显示底部水平辅助线
        console.log('对象移动事件触发:', guideLines.value.horizontalBottom);

        if (guideLines.value.horizontalBottom) {
          guideLines.value.horizontalBottom.style.display = 'block';
          guideLines.value.horizontalBottom.style.top =`${objTop + rulerOffset+(obj.y2/2)}px`;
        }
      }

      
      
      // 更新位置信息
      const leftMM = pxToMm(objLeft, pxPerMm.value);
      const topMM = pxToMm(objTop, pxPerMm.value);
      const rightMM = pxToMm(objRight, pxPerMm.value);
      const bottomMM = pxToMm(objBottom, pxPerMm.value);
      
      guideLines.value.info.textContent = `X: ${leftMM.toFixed(1)}mm, Y: ${topMM.toFixed(1)}mm, 宽: ${(rightMM-leftMM).toFixed(1)}mm, 高: ${(bottomMM-topMM).toFixed(1)}mm`;
      guideLines.value.info.style.display = 'block';
    });
    
    // 对象移动结束时隐藏辅助线
    window.globalCanvas.on('object:modified', () => {
      if (!guideLines.value.horizontal || !guideLines.value.vertical) return;
      
      // 隐藏辅助线和位置信息
      guideLines.value.horizontal.style.display = 'none';
      guideLines.value.vertical.style.display = 'none';
      if (guideLines.value.horizontalBottom) guideLines.value.horizontalBottom.style.display = 'none';
      if (guideLines.value.verticalRight) guideLines.value.verticalRight.style.display = 'none';
      guideLines.value.info.style.display = 'none';
    });
    
    window.globalCanvas.on('selection:cleared', () => {
      // 确保辅助线被隐藏
      if (guideLines.value.horizontal) guideLines.value.horizontal.style.display = 'none';
      if (guideLines.value.vertical) guideLines.value.vertical.style.display = 'none';
      if (guideLines.value.horizontalBottom) guideLines.value.horizontalBottom.style.display = 'none';
      if (guideLines.value.verticalRight) guideLines.value.verticalRight.style.display = 'none';
      if (guideLines.value.info) guideLines.value.info.style.display = 'none';
    });
  };

  // 处理双击事件，进入文本编辑模式
  const handleDoubleClick = (opt) => {
    console.log('双击事件', opt);
    // 如果没有选中对象，或者全局画布不可用，则退出
    if (!opt.target || !window.globalCanvas) {
      console.log('没有选中对象或画布不可用');
      return;
    }

    const obj = opt.target;
    console.log('双击的对象:', obj);

    try {
      // 判断是否为文本对象，只有文本对象才能编辑
      if (obj.type === 'textbox' || obj.type === 'i-text') {
        console.log('双击的是文本对象，启动编辑模式');

        // 获取鼠标点击的位置
        const pointer = window.globalCanvas.getPointer(opt.e);
        // 判断点击是否在对象内
        if (obj.containsPoint(pointer)) {
          // 确保对象能被编辑
          obj.editable = true;

          // 检查对象是否有toLocalPoint方法
          if (typeof obj.toLocalPoint === 'function') {
            // 计算点击位置相对于文本对象的偏移
            const localPoint = obj.toLocalPoint(pointer, 'center', 'center');
            const textWidth = obj.calcTextWidth();
            const fontSize = obj.fontSize;

            // 计算点击位置对应的字符索引
            let charIndex = Math.floor(localPoint.x / (fontSize * 0.6)); // 0.6是一个经验值，用于估算字符宽度
            charIndex = Math.max(0, Math.min(charIndex, obj.text.length));

            // 进入编辑模式并设置光标位置
            obj.enterEditing();
            obj.hiddenTextarea.selectionStart = charIndex;
            obj.hiddenTextarea.selectionEnd = charIndex;
          } else {
            // 如果没有toLocalPoint方法，简单进入编辑模式
            console.log('对象不支持toLocalPoint方法，使用默认编辑模式');
            obj.enterEditing();
          }
        }
      } else if (obj.type === 'image' && obj.fieldType === 'barcode') {
        // 处理条形码双击
        console.log('双击的是条形码对象，不支持直接编辑');
        ElMessage.info('条形码不支持直接编辑，请通过右侧面板修改');
      } else {
        console.log('双击的对象不支持编辑:', obj.type);
      }
    } catch (error) {
      console.error('启动编辑模式时出错:', error);
      // 尝试基本编辑模式
      try {
        if (obj.type === 'textbox' && typeof obj.enterEditing === 'function') {
          obj.enterEditing();
        }
      } catch (fallbackError) {
        console.error('备用编辑模式也失败:', fallbackError);
      }
    }
  };

  // 处理对象缩放事件，特别是文本对象
  const handleObjectScaling = (e) => {
    updateRulerDimensions();

    const obj = e.target;
    if (!obj) return;

    // 处理文本对象的缩放
    if ((obj.customType === 'text' || obj.customType === 'field') ||
      (obj.type === 'textbox' || obj.type === 'text' || obj.type === 'i-text')) {
      // 在Fabric 6.0+中，文本对象不能直接使用scaleX/Y缩放
      // 而是需要调整width属性
      // 更新对象坐标
      obj.setCoords();
    }
  };

  // 更新画布样式
  const updateCanvasStyles = () => {
    const canvasContainer = document.querySelector('.canvas-container');
    if (canvasContainer) {
      canvasContainer.style.border = '1px solid #dcdfe6';
      canvasContainer.style.boxShadow = '0 2px 12px 0 rgba(0, 0, 0, 0.1)';
      canvasContainer.style.position = 'relative';
      canvasContainer.style.zIndex = '5';
      canvasContainer.style.backgroundColor = '#ffffff';
    }
  };

  // 处理选中对象
  const handleObjectSelected = (e) => {
    const obj = e.selected[0];
    if (!obj) return;

    // 在Fabric 6.0+中，优先使用customType，如果没有则使用原生type
    const objType = obj.customType || obj.type;

    selectedObject.value = {
      type: objType,
      left: pxToMm(obj.left),
      top: pxToMm(obj.top),
      angle: Math.round(obj.angle || 0)
    };

    // 根据不同类型设置不同属性
    if ((objType === 'text' || objType === 'field') ||
      (objType === 'textbox' || objType === 'text' || objType === 'i-text')) {
      selectedObject.value.text = obj.text;
      selectedObject.value.fontSize = obj.fontSize;
      selectedObject.value.fontWeight = obj.fontWeight;
      selectedObject.value.fill = obj.fill;
    } else if (objType === 'image') {
      selectedObject.value.width = pxToMm(Math.round(obj.width * obj.scaleX));
      selectedObject.value.height = pxToMm(Math.round(obj.height * obj.scaleY));
    } else if (objType === 'rect') {
      selectedObject.value.width = pxToMm(Math.round(obj.width * obj.scaleX));
      selectedObject.value.height = pxToMm(Math.round(obj.height * obj.scaleY));
      selectedObject.value.fill = obj.fill;
      selectedObject.value.stroke = obj.stroke;
      selectedObject.value.strokeWidth = obj.strokeWidth;
    } else if (objType === 'line') {
      selectedObject.value.stroke = obj.stroke;
      selectedObject.value.strokeWidth = obj.strokeWidth;
    } else if (objType === 'barcode') {
      selectedObject.value.barcodeValue = obj.barcodeValue;
      selectedObject.value.barcodeFormat = obj.barcodeFormat;
      selectedObject.value.displayValue = obj.displayValue;
    } else if (objType === 'qrcode') {
      selectedObject.value.qrcodeValue = obj.qrcodeValue;
      selectedObject.value.qrcodeSize = obj.qrcodeSize;
    } else if (objType === 'table') {
      selectedObject.value.width = pxToMm(Math.round(obj.width * obj.scaleX));
      selectedObject.value.height = pxToMm(Math.round(obj.height * obj.scaleY));
    }

    onObjectSelected(selectedObject.value);
  };

  // 允许对象缩放和编辑，但禁用旋转
  const disableRotation = (e) => {
    const obj = e.target;
    if (obj) {
      // 禁用旋转，但允许缩放和编辑
      obj.lockRotation = true;

      // 显示所有控制点，但隐藏旋转控制点
      obj.setControlsVisibility({
        mt: true,  // middle top
        mb: true,  // middle bottom
        ml: true,  // middle left
        mr: true,  // middle right
        tl: true,  // top left
        tr: true,  // top right
        bl: true,  // bottom left
        br: true,  // bottom right
        mtr: false // rotate control - 禁用旋转控制
      });

      // Fabric 6.0+不再使用lockUniScaling，而是使用hasControls
      obj.hasControls = true;

      // 为文本对象启用编辑功能
      if ((obj.customType === 'text' || obj.customType === 'field') ||
        (obj.type === 'textbox' || obj.type === 'text' || obj.type === 'i-text')) {
        obj.editable = true;

        // 添加双击事件监听
        obj.on('mousedblclick', function () {
          // 确保使用正确的canvas引用
          const canvas = this.canvas || window.globalCanvas;
          if (canvas) {
            canvas.setActiveObject(this);
            this.enterEditing();

            // 如果对象有点击位置信息，设置光标位置
            if (this._lastClickPoint) {
              const charIndex = this.getSelectionStartFromPointer(this._lastClickPoint.x, this._lastClickPoint.y);
              this.setSelectionStart(charIndex);
              this.setSelectionEnd(charIndex);
              this.initDimensions();
              if (this.hiddenTextarea) {
                this.hiddenTextarea.selectionStart = charIndex;
                this.hiddenTextarea.selectionEnd = charIndex;
                this._updateTextarea();
              }
            }

            canvas.renderAll();
          }
        });
      }
    }
  };

  // 坐标转换函数 - 毫米转像素
  const mmToPx = (mm) => {
    if (!mm && mm !== 0) return 0;
    return mm * pxPerMm.value;
  };

  // 坐标转换函数 - 像素转毫米
  const pxToMm = (px) => {
    if (!px && px !== 0) return 0;
    return px / pxPerMm.value;
  };

  // 更新画布尺寸
  const updateCanvasSize = (widthMM, heightMM) => {
    if (!window.globalCanvas) {
      console.error('画布未初始化，无法更新尺寸');
      return;
    }

    console.log(`更新画布尺寸: 宽度=${widthMM}mm, 高度=${heightMM}mm, 比例=${pxPerMm.value}px/mm`);

    try {
      // 将毫米转换为像素
      const widthPx = mmToPx(widthMM);
      const heightPx = mmToPx(heightMM);

      console.log(`像素尺寸: ${widthPx}px x ${heightPx}px`);

      // 更新画布尺寸
      window.globalCanvas.setWidth(widthPx);
      window.globalCanvas.setHeight(heightPx);

      // 更新内容区域尺寸
      canvasContentWidth.value = widthMM;
      canvasContentHeight.value = heightMM;

      // 触发重新渲染
      window.globalCanvas.renderAll();

      // 更新刻度尺
      updateRulerDimensions();

      console.log('画布尺寸更新完成');
    } catch (error) {
      console.error('更新画布尺寸时出错:', error);
    }
  };


  // 添加对象到画布
  const addObject = (type, options = {}) => {
    const { left = 100, top = 100, fieldName } = options;

    switch (type) {
      case 'text':
        addText('示例文本', left, top);
        break;
      case 'field':
        addTextField(fieldName, left, top);
        break;
      case 'image':
        addImage(left, top);
        break;
      case 'barcode':
        addBarcode('1234567890', left, top);
        break;
      case 'qrcode':
        addQRCode('https://example.com', left, top);
        break;
      case 'line':
        addLine(left, top);
        break;
      case 'rect':
        addRect(left, top);
        break;
      case 'table':
        addTable(left, top);
        break;
    }
  };

  // 删除选中对象
  const deleteSelectedObject = (printFields) => {
    if (typeof window === 'undefined' || !window.globalCanvas) return;
    // 检查当前是否有对象被选中
    const activeObject = window.globalCanvas.getActiveObject();
    const activeObjects = window.globalCanvas.getActiveObjects();
    // 检查是否是文本对象且正在编辑状态
    if (activeObject && activeObject.type !== 'activeselection') {
      // 检查对象是否处于编辑状态
      if (activeObject.isEditing) {
        return; // 如果对象处于编辑状态，不执行删除操作
      }

      // 获取字段名称，用于同步取消右侧面板的选中状态
      let fieldName = null;
      if (activeObject.fieldName) {
        fieldName = activeObject.fieldName; // 文本字段
      } else if (activeObject.additionalInfo && activeObject.additionalInfo.code) {
        fieldName = activeObject.additionalInfo.code; // 条形码可能使用此属性
      } else if (activeObject.barcodeKey) {
        fieldName = activeObject.barcodeKey; // 条形码可能使用此属性
      }

      // 调用导入的删除函数
      handleFieldUnselected(activeObject.fieldName)
      printFields[activeObject.fieldName] = false;
    } else if (activeObject && activeObject.type === 'activeselection' && activeObjects.length > 0) {
      activeObjects.forEach(object => {
        if (object.fieldName) {
          handleFieldUnselected(object.fieldName);
          printFields[object.fieldName] = false;
        }
      });
    }
  };

  // 清空画布
  const clearCanvas = () => {
    if (!window.globalCanvas) return;

    window.globalCanvas.clear();
    window.globalCanvas.backgroundColor = '#ffffff';
    window.globalCanvas.renderAll();
  };

  // 更新刻度尺尺寸
  const updateRulerDimensions = () => {
    if (!window.globalCanvas) return;

    // 计算画布内容区域的边界
    const objects = window.globalCanvas.getObjects();
    let minX = Number.MAX_VALUE;
    let minY = Number.MAX_VALUE;
    let maxX = 0;
    let maxY = 0;

    // 初始边界至少是纸张大小
    minX = 0;
    minY = 0;
    maxX = window.globalCanvas.width;
    maxY = window.globalCanvas.height;

    // 遍历所有对象，找出最大范围
    if (objects.length > 0) {
      objects.forEach(obj => {
        // 在Fabric 6.0+中，优先使用customType，如果没有则使用原生type
        const objType = obj.customType || obj.type;
        if (objType === 'background') return;

        const objBounds = obj.getBoundingRect();
        minX = Math.min(minX, objBounds.left);
        minY = Math.min(minY, objBounds.top);
        maxX = Math.max(maxX, objBounds.left + objBounds.width);
        maxY = Math.max(maxY, objBounds.top + objBounds.height);
      });
    }

    // 将边界值转换为毫米
    const contentWidthMM = Math.max(pxToMm(maxX), canvasContentWidth.value);
    const contentHeightMM = Math.max(pxToMm(maxY), canvasContentHeight.value);

    // 更新内容尺寸
    canvasContentWidth.value = contentWidthMM;
    canvasContentHeight.value = contentHeightMM;

    console.log('更新刻度尺尺寸:', contentWidthMM, 'mm x', contentHeightMM, 'mm');
  };

  // 设置背景图
  const setBackgroundImage = (url, options = {}) => {
    if (!window.globalCanvas) return;

    window.fabric.Image.fromURL(url, (img) => {
      if (!img || !img.width || !img.height) {
        ElMessage.error('加载的图片无效');
        return;
      }

      const canvasWidth = window.globalCanvas.width;
      const canvasHeight = window.globalCanvas.height;

      const scale = Math.min(
        canvasWidth / img.width,
        canvasHeight / img.height
      );

      window.globalCanvas.setBackgroundImage(img, window.globalCanvas.renderAll.bind(window.globalCanvas), {
        scaleX: scale,
        scaleY: scale,
        opacity: options.opacity,
        left: canvasWidth / 2,
        top: canvasHeight / 2,
        originX: 'center',
        originY: 'center'
      });

      saved.value = false;
    }, {
      crossOrigin: 'Anonymous'
    });
  };

  // 移除背景图
  const removeBackgroundImage = () => {
    if (!window.globalCanvas) return;

    window.globalCanvas.setBackgroundImage(null, window.globalCanvas.renderAll.bind(window.globalCanvas));
    saved.value = false;
  };

  // 生成预览图片
  const generatePreview = () => {
    if (!window.globalCanvas) return '';

    return window.globalCanvas.toDataURL({
      format: 'png',
      quality: 1
    });
  };


  // 确保在更新条形码时保持缩放和交互功能
  const handleUpdatedObjects = (updatedObj) => {
    if (updatedObj) {
      // 确保对象可以自由缩放但不能旋转
      updatedObj.lockUniScaling = false;
      updatedObj.lockRotation = true;
      updatedObj.hasControls = true;

      // 设置统一的控制点样式
      updatedObj.set({
        borderColor: '#5E9ED6',
        cornerColor: '#5E9ED6',
        cornerSize: 6,
        transparentCorners: false
      });

      // 禁用旋转控制点
      updatedObj.setControlsVisibility({
        mt: true,  // middle top
        mb: true,  // middle bottom
        ml: true,  // middle left
        mr: true,  // middle right
        tl: true,  // top left
        tr: true,  // top right
        bl: true,  // bottom left
        br: true,  // bottom right
        mtr: false // rotate control - 禁用旋转控制
      });
    }

    return updatedObj;
  };

  // 添加表格
  const addTable = (left, top, options = {}) => {
    // 检查画布是否已初始化
    if (!window.globalCanvas) {
      console.error('画布未初始化，无法添加表格');
      return null;
    }

    try {
      // 表格配置
      const tableConfig = {
        key: options.key,
        label: options.label, 
        rows: options.rows || 3,           // 默认3行
        cols: options.cols || 3,           // 默认3列
        cellWidthMM: Math.round(options.cellWidth) || 15,  // 默认单元格宽度15mm
        cellHeightMM: Math.round(options.cellHeight) || 10, // 默认单元格高度10mm
        strokeColor: options.strokeColor || '#000000', // 默认黑色线条
        strokeWidth: options.strokeWidth || 1,  // 默认线宽1px
        fieldName: options.fieldName || `table_${Date.now()}`,
        // 表头相关配置
        hasHeader: options.hasHeader === true,
        headerBackgroundColor: options.headerBackgroundColor || '#f2f2f2',
        headerTextColor: options.headerTextColor || '#333333',
        headerFontSize: options.headerFontSize || 12,
        headerBold: options.headerBold === true,
        headers: options.headers || [],
        // 表格数据
        tableData: options.tableData || [],
        customData: options.customData
      };

      // 数据校验和处理
      if (tableConfig.hasHeader && !tableConfig.headers.length) {
        // 如果未指定表头但启用了表头，创建默认表头
        for (let i = 0; i < tableConfig.cols; i++) {
          tableConfig.headers.push({
            key: `col_${i+1}`,
            label: `列 ${i+1}`,
            width: tableConfig.cellWidthMM
          });
        }
      }

      // 根据表头调整列宽（如果有表头配置）
      let columnWidths = [];
      if (tableConfig.hasHeader && tableConfig.headers.length > 0) {
        // 使用表头中定义的宽度
        columnWidths = tableConfig.headers.map(header => header.width || tableConfig.cellWidthMM);
        
        // 确保列数与表头数一致
        tableConfig.cols = tableConfig.headers.length;
      } else {
        // 如果没有表头，使用默认宽度
        for (let i = 0; i < tableConfig.cols; i++) {
          columnWidths.push(tableConfig.cellWidthMM);
        }
      }

      // 计算表格总宽高(毫米)
      const tableWidthMM = columnWidths.reduce((sum, width) => sum + width, 0);
      const tableHeightMM = tableConfig.rows * tableConfig.cellHeightMM + 
                           (tableConfig.hasHeader ? tableConfig.cellHeightMM : 0);

      // 创建存储所有元素的数组
      const tableElements = [];
      
      // 计算每一列的起始X坐标
      let columnStartX = [0];
      let accumulatedWidth = 0;
      
      for (let i = 0; i < columnWidths.length - 1; i++) {
        accumulatedWidth += columnWidths[i];
        columnStartX.push(accumulatedWidth);
      }

      // 创建水平线
      const totalRows = tableConfig.rows + (tableConfig.hasHeader ? 1 : 0);
      for (let i = 0; i <= totalRows; i++) {
        const y = top + mmToPx(i * tableConfig.cellHeightMM);
        const horizontalLine = new window.fabric.Line(
          [left, y, left + mmToPx(tableWidthMM), y], 
          {
            stroke: tableConfig.strokeColor,
            strokeWidth: tableConfig.strokeWidth,
            selectable: false
          }
        );
        tableElements.push(horizontalLine);
      }
      
      // 创建垂直线
      let currentX = left;
      for (let j = 0; j <= tableConfig.cols; j++) {
        // 当j > 0时，累加前一列的宽度
        if (j > 0) {
          currentX += mmToPx(columnWidths[j-1]);
        }
        
        const verticalLine = new window.fabric.Line(
          [currentX, top, currentX, top + mmToPx(tableHeightMM)], 
          {
            stroke: tableConfig.strokeColor,
            strokeWidth: tableConfig.strokeWidth,
            selectable: false
          }
        );
        tableElements.push(verticalLine);
      }
      
      // 如果有表头，添加表头背景和文字
      if (tableConfig.hasHeader) {
        // 注意：不再添加表头背景填充，因为打印机不支持背景色
        // 直接添加表头文字
        currentX = left;
        for (let j = 0; j < tableConfig.headers.length; j++) {
          const header = tableConfig.headers[j];
          const columnWidth = mmToPx(columnWidths[j]);
          
          // 列中心点
          const columnCenter = currentX + columnWidth / 2;
          
          // 创建表头文字
          const headerText = new window.fabric.Text(header.label, {
            left: columnCenter,
            top: top + mmToPx(tableConfig.cellHeightMM / 2),
            fontFamily: 'Arial',
            fontSize: tableConfig.headerFontSize,
            fontWeight: tableConfig.headerBold ? 'bold' : 'normal',
            fill: tableConfig.headerTextColor,
            textAlign: 'center',
            originX: 'center',
            originY: 'center',
            selectable: false
          });
          tableElements.push(headerText);
          
          // 更新当前X坐标
          currentX += columnWidth;
        }
      }
      
      // 添加表格数据内容
      if (tableConfig.tableData && tableConfig.tableData.length > 0) {
        // 确定实际要展示的数据行数：取用户配置的行数和实际数据行数中的较小值
        const actualRows = Math.min(tableConfig.rows, tableConfig.tableData.length);
        
        // 遍历数据行
        for (let rowIndex = 0; rowIndex < actualRows; rowIndex++) {
          const rowData = tableConfig.tableData[rowIndex];
          const rowStartY = top + mmToPx((tableConfig.hasHeader ? 1 : 0) * tableConfig.cellHeightMM); // 如果有表头，从第二行开始
          
          // 当前行的Y坐标
          const rowY = rowStartY + mmToPx(rowIndex * tableConfig.cellHeightMM);
          
          // 重置X坐标为表格左侧
          let dataX = left;
          
          // 遍历表头配置，渲染对应的数据单元格
          for (let colIndex = 0; colIndex < tableConfig.headers.length; colIndex++) {
            const header = tableConfig.headers[colIndex];
            const columnWidth = mmToPx(columnWidths[colIndex]);
            
            // 列中心点
            const columnCenter = dataX + columnWidth / 2;
            
            // 获取单元格内容
            const cellContent = rowData[header.key] || ''; // 如果没有对应的数据，显示空字符串
            
            // 计算行中心点
            const cellY = rowY + mmToPx(tableConfig.cellHeightMM / 2);
            
            // 创建单元格文本
            const cellText = new window.fabric.Text(cellContent, {
              left: columnCenter,
              top: cellY,
              fontFamily: 'Arial',
              fontSize: tableConfig.headerFontSize,
              fill: '#000000',
              textAlign: 'center',
              originX: 'center',
              originY: 'center',
              selectable: false
            });
            tableElements.push(cellText);
            
            // 更新下一列的X坐标
            dataX += columnWidth;
          }
        }
      }
      
      // 将所有元素组合成一个组
      const tableGroup = new window.fabric.Group(tableElements, {
        left: left,
        top: top,
        originX: 'left',
        originY: 'top',
        borderColor: '#5E9ED6',
        cornerColor: '#5E9ED6',
        cornerSize: 6,
        transparentCorners: false,
        hasControls: true,
        lockRotation: true,
        customType: 'table',
        fieldName: tableConfig.fieldName,
        tableData: {
          rows: tableConfig.rows,
          cols: tableConfig.cols,
          hasHeader: tableConfig.hasHeader,
          headers: tableConfig.headers,
          columnWidths: columnWidths,
          cellHeight: tableConfig.cellHeightMM,
          data: tableConfig.tableData // 保存表格数据
        },
        customData: tableConfig.customData
      });

      // 由于group的创建方式，需要重新定位group
      tableGroup.set({
        left: left,
        top: top
      });

      // 禁用旋转控制点
      tableGroup.setControlsVisibility({
        mt: false,  // middle top
        mb: false,  // middle bottom
        ml: false,  // middle left
        mr: false,  // middle right
        tl: true,  // top left
        tr: true,  // top right
        bl: true,  // bottom left
        br: true,  // bottom right
        mtr: false // rotate control - 禁用旋转控制
      });

      window.globalCanvas.add(tableGroup);
      window.globalCanvas.setActiveObject(tableGroup);
      window.globalCanvas.renderAll();

      // 标记为未保存状态
      saved.value = false;
      
      console.log(`成功添加表格: ${tableConfig.rows}行×${tableConfig.cols}列，${tableConfig.hasHeader ? '有' : '无'}表头，数据行数: ${tableConfig.tableData?.length || 0}`);
      
      return tableGroup;
    } catch (error) {
      console.error('添加表格时出错:', error);
      return null;
    }
  };

  // 添加文本
  const addText = (text, left, top, options = {}) => {
    // 检查画布是否已初始化
    if (!window.globalCanvas) {
      console.error('画布未初始化，无法添加文本');
      return null;
    }

    try {
      // 默认设置
      const fontSize = options.fontSize || 16;
      const width = options.width || mmToPx(30);
      const customHeight = options.customHeight || mmToPx(15);
      const fontWeight = options.fontWeight || 'normal';
      const fill = options.fill || '#000000';

      // 创建文本对象
      const textObj = new window.fabric.Textbox(text, {
        left:Math.round(left),
        top:Math.round(top),
        fontSize,
        fontWeight,
        fill,
        width,
        customHeight,
        _initialFontSize: fontSize, // 存储初始字体大小，用于在缩放时保持不变
        originX: options.originX || 'center',
        originY: options.originY || 'center',
        editable: true,
        hasControls: true,
        splitByGrapheme: false,
        borderColor: '#5E9ED6',
        cornerColor: '#5E9ED6',
        cornerSize: 6,
        transparentCorners: false,
        lockRotation: true,
        // 添加多行文本支持
        breakWords: true,       // 允许在单词之间换行
        textAlign: 'left',      // 文本左对齐
        lineHeight: 1.2,        // 行高
        charSpacing: 0,         // 字符间距
        minWidth: 20,           // 最小宽度
        // 启用文本换行功能
        isWrapping: true,       // 启用文本自动换行 
        splitByGrapheme: false, // 按字符拆分而不是按单词拆分
        styles: {},             // 初始化样式对象
        fieldName: options.fieldName || '',
        fieldType: options.fieldType || 'text',
        textTemplate: options.textTemplate || '',
        customData: options.customData || {}  
      });

      // 添加自定义类型标识
      textObj.customType = 'text';

      // 禁用旋转控制点
      textObj.setControlsVisibility({
        mt: false,  // middle top
        mb: false,  // middle bottom
        ml: true,  // middle left
        mr: true,  // middle right
        tl: true,  // top left
        tr: true,  // top right
        bl: true,  // bottom left
        br: true,  // bottom right
        mtr: false // rotate control - 禁用旋转控制
      });

      // 设置边框（如果有边框选项）
      if (options.border) {
        textObj.setBorder({
          show: options.border.show !== false,
          color: options.border.color || '#000000',
          width: options.border.width || 1,
          dashArray: options.border.dashArray || null,
          padding: options.border.padding !== undefined ? options.border.padding : 5,
          // 明确设置边框方向为布尔值
          top: options.border.top === true,
          right: options.border.right === true,
          bottom: options.border.bottom === true,
          left: options.border.left === true
        });
      }

      // 初始化鼠标事件
      if (typeof textObj.initMousedownHandler === 'function') {
        textObj.initMousedownHandler();
      } else {
        console.warn('文本对象不支持initMousedownHandler方法');
      }

      // 应用自定义高度
      if (typeof textObj._applyCustomHeight === 'function') {
        textObj._applyCustomHeight();
      } else {
        console.warn('文本对象不支持_applyCustomHeight方法');
      }

      // 确保文本对象有换行按钮功能
      if (typeof textObj.addNewlineButton === 'function') {
        // 先添加到画布，以便能够初始化换行按钮
        window.globalCanvas.add(textObj);

        // 设置一个短暂的延时，确保canvas引用已正确设置
        setTimeout(() => {
          if (!textObj._newlineButtonAdded) {
            textObj.addNewlineButton();
          }
        }, 50);
      } else {
        // 添加到画布
        window.globalCanvas.add(textObj);
      }

      window.globalCanvas.setActiveObject(textObj);
      window.globalCanvas.renderAll();

      // 标记为未保存状态
      saved.value = false;

      console.log('成功添加文本对象:', textObj);

      return textObj;
    } catch (error) {
      console.error('添加文本时出错:', error);
      return null;
    }
  };

  // 添加字段
  const addTextField = (fieldName, left, top, options = {}) => {
    const displayText = {
      receiverName: '收件人: [收件人姓名]',
      receiverPhone: '电话: [收件人电话]',
      receiverAddress: '地址: [收件人地址]',
      senderName: '寄件人: [寄件人姓名]',
      senderPhone: '电话: [寄件人电话]',
      senderAddress: '地址: [寄件人地址]',
      expressNo: '快递单号: [快递单号]',
      weight: '重量: [重量]kg',
      orderNo: '订单号: [订单号]',
      createTime: '创建时间: [创建时间]'
    }[fieldName] || `[${fieldName}]`;

    // 创建文本对象
    const textObj = new window.fabric.Textbox(displayText, {
      left,
      top,
      fontSize: 14,
      _initialFontSize: 14, // 存储初始字体大小
      fontWeight: 'normal',
      fill: '#000000',
      width: mmToPx(40),
      customHeight: mmToPx(15), // 设置自定义高度
      fieldName: fieldName,
      originX: 'center',
      originY: 'center',
      editable: true,
      hasControls: true,
      splitByGrapheme: false,
      borderColor: '#5E9ED6',
      cornerColor: '#5E9ED6',
      cornerSize: 6,
      transparentCorners: false,
      lockRotation: true,
      // 添加多行文本支持
      breakWords: true,       // 允许在单词之间换行
      textAlign: 'left',      // 文本左对齐
      lineHeight: 1.2,        // 行高
      charSpacing: 0,         // 字符间距
      minWidth: 20,           // 最小宽度
      // 启用文本换行功能
      isWrapping: true,       // 启用文本自动换行
      splitByGrapheme: false, // 按字符拆分而不是按单词拆分
      styles: {},             // 初始化样式对象
    });

    // 在Fabric 6.0+中，type是只读属性，需要使用自定义属性
    textObj.customType = 'field';

    // 禁用旋转控制点
    textObj.setControlsVisibility({
      mt: true,  // middle top
      mb: true,  // middle bottom
      ml: true,  // middle left
      mr: true,  // middle right
      tl: true,  // top left
      tr: true,  // top right
      bl: true,  // bottom left
      br: true,  // bottom right
      mtr: false // rotate control - 禁用旋转控制
    });

    // 初始化鼠标事件
    textObj.initMousedownHandler();

    // 应用自定义高度
    textObj._applyCustomHeight();

    // 设置边框 - 添加边框设置
    if (options && options.border) {
      textObj.setBorder({
        show: options.border.show !== false,
        color: options.border.color || '#000000',
        width: options.border.width || 1,
        dashArray: options.border.dashArray || null,
        padding: options.border.padding !== undefined ? options.border.padding : 5,
        // 添加对边框方向的支持
        top: options.border.top !== false && options.border.top !== undefined ? options.border.top : options.border.show !== false,
        right: options.border.right !== false && options.border.right !== undefined ? options.border.right : options.border.show !== false,
        bottom: options.border.bottom !== false && options.border.bottom !== undefined ? options.border.bottom : options.border.show !== false,
        left: options.border.left !== false && options.border.left !== undefined ? options.border.left : options.border.show !== false
      });
    } else {
      // 默认边框设置
      textObj.setBorder({
        show: true,
        color: '#333333',
        width: 1
      });
    }

    // 确保字段文本对象有换行按钮功能
    if (typeof textObj.addNewlineButton === 'function') {
      // 先添加到画布，以便能够初始化换行按钮
      window.globalCanvas.add(textObj);

      // 设置一个短暂的延时，确保canvas引用已正确设置
      setTimeout(() => {
        if (!textObj._newlineButtonAdded) {
          textObj.addNewlineButton();
        }
      }, 50);
    } else {
      // 添加到画布
      window.globalCanvas.add(textObj);
    }

    window.globalCanvas.setActiveObject(textObj);
    window.globalCanvas.renderAll();

    // 标记为未保存状态
    saved.value = false;

    return textObj;
  };

  // 添加线条
  const addLine = (left, top, options = {}) => {
    // 检查画布是否已初始化
    if (!window.globalCanvas) {
      console.error('画布未初始化，无法添加水平线');
      return null;
    }

    try {
      
      const lineArray =[];
      // 计算线条长度（默认为画布宽度的一半）
      options.Line.forEach(item => {  
        if(item>0){
          item = mmToPx(item);
        }
        lineArray.push(item);
      });

      const time = new Date().getTime();
      const key = options.key+'_'+time;

      const line = new window.fabric.Line(lineArray, {
        left:Math.round(left),
        top:top,
        stroke: options.stroke || '#000000',
        strokeWidth: options.strokeWidth || 1,
        strokeDashArray: options.strokeDashArray || null, // 实线
        originX: options.originX || 'left', // 改为left使线条起点位于指定位置
        originY: options.originY || 'center',
        borderColor: options.borderColor || '#5E9ED6',
        cornerColor: options.cornerColor || '#5E9ED6',
        cornerSize: options.cornerSize || 6,
        transparentCorners: options.transparentCorners || false,
        hasControls: options.hasControls || true,
        customType: options.customType || 'horizontalLine',
        fieldName: key || '',
        textTemplate: options.textTemplate || '',
        customData:{...options}
      });
     
      if (options.customType === 'horizontalLine') {
        // 禁用旋转控制点，只允许水平方向的调整
        line.setControlsVisibility({
          mt: false,  // middle top
          mb: false,  // middle bottom
          ml: true,   // middle left
          mr: true,   // middle right
          tl: false,  // top left
          tr: false,  // top right
          bl: false,  // bottom left
          br: false,  // bottom right
          mtr: false  // rotate control - 禁用旋转控制
        });
      } else if (options.customType === 'verticalLine') {
        // 禁用旋转控制点，只允许垂直方向的调整
        line.setControlsVisibility({
          mt: true,  // middle top
          mb: true,  // middle bottom
          ml: false,  // middle left
          mr: false,  // middle right
          tl: false,  // top left
          tr: false,  // top right
          bl: false,  // bottom left
          br: false,  // bottom right
          mtr: false  // rotate control - 禁用旋转控制
        });
      }

      window.globalCanvas.add(line);
      window.globalCanvas.setActiveObject(line);
      window.globalCanvas.renderAll();

      // 标记为未保存状态
      saved.value = false;

      console.log(`成功添加${options.label}:`, line);

      return line;
    } catch (error) {
      console.error(`添加${options.label}时出错:`, error);
      return null;
    }
  };

  // 添加矩形
  const addRect = (left, top) => {
    const rect = new window.fabric.Rect({
      left,
      top,
      width: mmToPx(30),
      height: mmToPx(20),
      fill: 'transparent',
      stroke: '#000000',
      strokeWidth: 1,
      originX: 'center',
      originY: 'center',
      borderColor: '#5E9ED6',
      cornerColor: '#5E9ED6',
      cornerSize: 6,
      transparentCorners: false,
      hasControls: true, // Fabric 6.0+使用hasControls替代lockUniScaling
      lockRotation: true // 禁用旋转
    });

    // 在Fabric 6.0+中，type是只读属性，需要使用自定义属性
    rect.customType = 'rect';

    // 禁用旋转控制点
    rect.setControlsVisibility({
      mt: true,  // middle top
      mb: true,  // middle bottom
      ml: true,  // middle left
      mr: true,  // middle right
      tl: true,  // top left
      tr: true,  // top right
      bl: true,  // bottom left
      br: true,  // bottom right
      mtr: false // rotate control - 禁用旋转控制
    });

    window.globalCanvas.add(rect);
    window.globalCanvas.setActiveObject(rect);
    window.globalCanvas.renderAll();

    // 标记为未保存状态
    saved.value = false;
  };

  // 添加图片
  const addImage = (left, top) => {
    // 打开文件选择对话框
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';

    input.onchange = (e) => {
      if (!e.target.files || !e.target.files[0]) return;

      const file = e.target.files[0];
      const reader = new FileReader();

      reader.onload = (event) => {
        const imgUrl = event.target.result;

        window.fabric.Image.fromURL(imgUrl, (img) => {
          // 设置图片大小和位置
          const maxWidth = mmToPx(50);  // 最大宽度50mm
          const maxHeight = mmToPx(50); // 最大高度50mm

          // 计算缩放比例
          let scale = 1;
          if (img.width > maxWidth || img.height > maxHeight) {
            scale = Math.min(maxWidth / img.width, maxHeight / img.height);
          }

          img.set({
            left,
            top,
            scaleX: scale,
            scaleY: scale,
            originX: 'center',
            originY: 'center',
            borderColor: '#5E9ED6',
            cornerColor: '#5E9ED6',
            cornerSize: 6,
            transparentCorners: false,
            hasControls: true, // Fabric 6.0+使用hasControls替代lockUniScaling
            lockRotation: true // 禁用旋转
          });

          // 在Fabric 6.0+中，type是只读属性，需要使用自定义属性
          img.customType = 'image';

          // 禁用旋转控制点
          img.setControlsVisibility({
            mt: true,  // middle top
            mb: true,  // middle bottom
            ml: true,  // middle left
            mr: true,  // middle right
            tl: true,  // top left
            tr: true,  // top right
            bl: true,  // bottom left
            br: true,  // bottom right
            mtr: false // rotate control - 禁用旋转控制
          });

          window.globalCanvas.add(img);
          window.globalCanvas.setActiveObject(img);
          window.globalCanvas.renderAll();

          // 标记为未保存状态
          saved.value = false;
        });
      };

      reader.readAsDataURL(file);
    };

    input.click();
  };

  // 处理字段被选中事件
  const handleFieldSelected = (fieldConfig) => {
    console.log('处理字段选择事件:', fieldConfig);

    try {
      // 检查canvas是否已初始化
      if (!window.globalCanvas) {
        console.error('画布未初始化，尝试重新初始化');
        // 尝试初始化画布
        const canvasElement = document.getElementById('designer-canvas');
        const scale = window.devicePixelRatio;

        if (canvasElement) {
          console.log('找到canvas元素，尝试初始化');

          // 如果已存在window.globalCanvas但状态不正确，先销毁
          if (window.globalCanvas) {
            try {
              window.globalCanvas.dispose();
              console.log('已销毁旧的Canvas实例');
            } catch (err) {
              console.warn('销毁Canvas实例时出错:', err);
            }
          }

          // 重新创建fabric.Canvas实例
          window.globalCanvas = new window.fabric.Canvas('designer-canvas', {
            width: canvasElement.width* scale,
            height: canvasElement.height* scale,
            backgroundColor: '#ffffff',
            selection: true,
            zoom: scale
          });

          console.log('重新初始化画布成功');
        } else {
          console.error('找不到canvas元素，无法初始化画布');
          return;
        }
      }

      // 获取字段位置坐标，转换为像素
      const position = fieldConfig.position || { x: 20, y: 20 };
      const left = mmToPx(position.x);
      const top = mmToPx(position.y);

      console.log(`添加字段 ${fieldConfig.key} 到位置 (${left}, ${top}), 类型: ${fieldConfig.type}`);

      if (fieldConfig.type === 'barcode') {
        console.log('添加条形码字段:', fieldConfig);
        console.log('当前画布状态:', window.globalCanvas ? '已初始化' : '未初始化');

        try {
          // 使用新的addBarcode方法添加条码
          const sampleContent = fieldConfig.sampleContent || '1234567890'; // 默认内容

          // 从设计器模式传入实际条码值
          const actualContent = fieldConfig.barcodeValue || sampleContent;

          console.log(`添加条形码: "${actualContent}", 宽度=${fieldConfig.width || 60}mm, 高度=${fieldConfig.height || 15}mm`);

          addBarcode(actualContent, left, top, {
            width: fieldConfig.width || 60,
            height: fieldConfig.height || 15,
            format: fieldConfig.barcodeFormat || 'CODE128',
            displayValue: fieldConfig.displayValue !== false,
            fieldName: fieldConfig.key,
            originX: 'left',
            originY: 'top',
            textTemplate: fieldConfig.textTemplate || '${data}',
            customData: { ...fieldConfig }
          }).then(barcodeObj => {
            console.log(`条形码 ${fieldConfig.label} 添加成功:`, barcodeObj);
          }).catch(error => {
            console.error(`条形码添加失败:`, error);
            ElMessage.error(`添加条形码 ${fieldConfig.label} 失败: ${error.message}`);
          });

          saved.value = false;
        } catch (error) {
          console.error(`添加条形码失败:`, error);
          ElMessage.error(`添加条形码 ${fieldConfig.label} 失败: ${error.message}`);
        }

        return;
      } else if (fieldConfig.type === 'line') {
        addLine(left, top, fieldConfig);
        return;
      } else if (fieldConfig.type === 'table') {
        // 添加表格字段
        try {
          console.log('添加表格字段:', fieldConfig);
          
          // 获取表格配置参数
          const tableOptions = {
            key: fieldConfig.key,
            label: fieldConfig.label,
            type: fieldConfig.type,
            rows: fieldConfig.rows || 3,
            cols: fieldConfig.cols || 3,
            cellWidth: fieldConfig.cellWidth || 15,
            cellHeight: fieldConfig.cellHeight || 10,
            strokeColor: fieldConfig.strokeColor || '#000000',
            strokeWidth: fieldConfig.strokeWidth || 1,
            fieldName: fieldConfig.key,
            // 表头相关配置
            hasHeader: fieldConfig.hasHeader === true,
            headerBackgroundColor: fieldConfig.headerBackgroundColor || '#f2f2f2',
            headerTextColor: fieldConfig.headerTextColor || '#333333',
            headerFontSize: fieldConfig.headerFontSize || 12,
            headerBold: fieldConfig.headerBold === true,
            headers: fieldConfig.headers || [],
            // 表格数据
            tableData: fieldConfig.tableData || [],
            customData: {...fieldConfig}
          };
          
          // 调用addTable函数创建表格
          const tableObj = addTable(left, top, tableOptions);
          
          if (tableObj) {
            console.log(`表格 ${fieldConfig.key} 添加成功:`, tableObj);
          } else {
            console.error(`表格添加失败`);
          }
          
          saved.value = false;
        } catch (tableErr) {
          console.error('添加表格时出错:', tableErr);
          ElMessage.error(`添加表格 ${fieldConfig.label} 失败: ${tableErr.message}`);
        }
        
        return;
      } else if (fieldConfig.type === 'text') {
        // 添加文本字段，使用textTemplate作为显示内容
        try {
          console.log('添加文本字段:', fieldConfig);
          // 使用原始textTemplate内容，不替换占位符
          const displayText = fieldConfig.textTemplate
            ? fieldConfig.textTemplate
            : `${fieldConfig.label}: ${fieldConfig.key}`;

          console.log('显示文本:', displayText);

          // 边框设置
          const borderOptions = fieldConfig.border || {
            show: true,           // 默认显示边框
            color: '#333333',     // 默认边框颜色
            width: 1,             // 默认边框宽度
            dashArray: null,      // 默认实线
            padding: 8,           // 默认8像素的内边距
            // 添加方向控制
            top: fieldConfig.border?.top === true,
            right: fieldConfig.border?.right === true,
            bottom: fieldConfig.border?.bottom === true,
            left: fieldConfig.border?.left === true
          };
          console.log('显示对象:', fieldConfig);

          // 字体大小
          const fontSize = fieldConfig.style ? fieldConfig.style.fontSize : 14;
          // 使用更新后的addText方法添加文本字段
          addText(displayText, left, top, {
            fontSize: fontSize,
            fontWeight: fieldConfig.style && fieldConfig.style.bold ? 'bold' : 'normal',
            fill: fieldConfig.style ? fieldConfig.style.color : '#000000',
            width: mmToPx(fieldConfig.width),
            customHeight: mmToPx(fieldConfig.height),
            originX: 'left',
            originY: 'top',
            border: borderOptions,
            customType: 'field',
            fieldName: fieldConfig.key,
            fieldType: 'text',
            textTemplate: fieldConfig.textTemplate,
            customData: { ...fieldConfig }
          });

          saved.value = false;
            console.log(`文本字段 ${fieldConfig.key} 已添加到画布，使用模板: ${fieldConfig.textTemplate}`);
        } catch (textErr) {
          console.error('添加文本字段时出错:', textErr);
        }
      }


    } catch (error) {
      console.error('添加字段到画布时出错:', error);
      console.error('错误详情:', error.message);
      console.error('错误堆栈:', error.stack);
      // 显示错误提示
      if (typeof window !== 'undefined' && window.ElMessage) {
        window.ElMessage.error(`添加字段失败: ${error.message}`);
      }
    }
  };

  // 处理字段取消选择事件
  const handleFieldUnselected = (key) => {
    if (!window.globalCanvas) return;

    try {
      // 查找画布上匹配字段名的对象
      const objects = window.globalCanvas.getObjects();

      const fieldObjects = objects.filter(obj =>
        obj.fieldName === key
      );
      if (fieldObjects.length > 0) {
        // 找到匹配的字段对象，从画布中移除
        fieldObjects.forEach(obj => {
          window.globalCanvas.remove(obj);
        });

        window.globalCanvas.discardActiveObject();
        window.globalCanvas.renderAll();

        saved.value = false;
        console.log(`字段 ${key} 已从画布移除`);
      }
    } catch (error) {
      console.error('从画布移除字段时出错:', error);
    }
  };

  // 组件销毁时移除事件监听
  onBeforeUnmount(() => {
    // 清理其他可能的引用
    if (window.globalCanvas) {
      window.globalCanvas.off();
    }
  });

  // 添加条形码
  const addBarcode = (value, left, top, options = {}) => {
    if (!window.globalCanvas) return null;

    try {
      // 创建临时canvas用于生成条形码
      const tempCanvas = document.createElement('canvas');
      tempCanvas.width = 800;
      tempCanvas.height = 200;
      tempCanvas.style.display = 'none';
      document.body.appendChild(tempCanvas);

      // 设置条形码内容
      const content = value || "1234567890";

      // 固定条形码整体宽度（毫米）和高度（毫米）
      const barcodeWidthMM = options.width || 60; // 默认60毫米宽
      const barcodeHeightMM = options.height || 15; // 默认15毫米高

      // 转换为像素
      const barcodeWidthPx = mmToPx(barcodeWidthMM);
      const barcodeHeightPx = mmToPx(barcodeHeightMM);

      // 根据内容长度动态计算条宽度
      const moduleWidth = 2; // 使用固定的模块宽度
      const margin = 10; // 固定的边距

      console.log(`条形码参数: 内容="${content}", 宽度=${barcodeWidthPx}px(${barcodeWidthMM}mm), 高度=${barcodeHeightPx}px(${barcodeHeightMM}mm)`);

      // 生成条形码
      JsBarcode(tempCanvas, content, {
        format: options.format || 'CODE128',
        width: moduleWidth,
        height: barcodeHeightPx - 30, // 留出底部空间显示文本
        displayValue: options.displayValue !== false,
        fontSize: 14,
        textMargin: 5,
        margin: margin,
        background: '#FFFFFF',
        lineColor: '#000000'
      });

      // 获取图像数据
      const dataUrl = tempCanvas.toDataURL('image/png');
      document.body.removeChild(tempCanvas);

      // 创建一个Promise并返回，以便处理异步图像加载
      return new Promise((resolve, reject) => {
        // 创建图像对象
        fabric.Image.fromURL(dataUrl)
          .then(img => {
            if (!img) {
              console.error('创建条形码图片对象失败');
              reject(new Error('创建条形码图片对象失败'));
              return;
            }

            // 计算缩放比例，确保宽度为目标宽度
            const scaleX = barcodeWidthPx / img.width;
            const scaleY = barcodeHeightPx / img.height;

            console.log(`原始尺寸: ${img.width}px x ${img.height}px, 缩放比例: X=${scaleX}, Y=${scaleY}`);

            // 设置图片属性
            img.set({
              left:Math.round(left),
              top:Math.round(top),
              scaleX: scaleX,
              scaleY: scaleY,
              originX: options.originX || 'center',
              originY: options.originY || 'center',
              borderColor: '#5E9ED6',
              cornerColor: '#5E9ED6',
              cornerSize: 6,
              transparentCorners: false,
              hasControls: true,
              lockRotation: true,
              customType: 'barcode',
              barcodeValue: content,
              barcodeFormat: options.format || 'CODE128',
              displayValue: options.displayValue !== false,
              barcodeWidth: barcodeWidthMM,
              barcodeHeight: barcodeHeightMM,
              fieldName: options.fieldName || '',
              fieldType: 'barcode',
              textTemplate: options.textTemplate || '${data}',
              customData: options.customData || {}
            });

            // 禁用旋转控制点
            img.setControlsVisibility({
              mt: false,  // middle top
              mb: false,  // middle bottom
              ml: false,   // middle left
              mr: false,   // middle right
              tl: true,   // top left
              tr: true,   // top right
              bl: true,   // bottom left
              br: true,   // bottom right
              mtr: false  // rotate control - 禁用旋转控制
            });

            window.globalCanvas.add(img);
            window.globalCanvas.setActiveObject(img);
            window.globalCanvas.renderAll();
            saved.value = false;

            resolve(img);
          })
          .catch(error => {
            console.error('加载条形码图片失败:', error);
            reject(error);
          });
      });
    } catch (error) {
      console.error('添加条形码时出错:', error);
      return Promise.reject(error);
    }
  };

  /**
   * 初始化辅助线DOM元素
   */
  const initGuideLines = () => {
    // 获取canvas容器
    const canvasWrapper = document.querySelector('.canvas-wrapper');
    if (!canvasWrapper) return;
    
    // 创建水平辅助线
    const horizontalLine = document.createElement('div');
    horizontalLine.className = 'guideline horizontal-guideline';
    horizontalLine.style.cssText = `
      position: absolute;
      height: 1px;
      width: 200%;
      background: transparent;
      border-top: 1px dashed #2196F3;
      pointer-events: none;
      display: none;
      z-index: 1000;
      left: -50%;
    `;
    
    // 创建底部水平辅助线
    const horizontalBottomLine = document.createElement('div');
    horizontalBottomLine.className = 'guideline horizontal-bottom-guideline';
    horizontalBottomLine.style.cssText = `
      position: absolute;
      height: 1px;
      width: 200%;
      background: transparent;
      border-top: 1px dashed #FF9800;
      pointer-events: none;
      display: none;
      z-index: 1000;
      left: -50%;
    `;
    
    // 创建垂直辅助线
    const verticalLine = document.createElement('div');
    verticalLine.className = 'guideline vertical-guideline';
    verticalLine.style.cssText = `
      position: absolute;
      width: 1px;
      height: 200%;
      background: transparent;
      border-left: 1px dashed #2196F3;
      pointer-events: none;
      display: none;
      z-index: 1000;
      top: -50%;
    `;
    
    // 创建右侧垂直辅助线
    const verticalRightLine = document.createElement('div');
    verticalRightLine.className = 'guideline vertical-right-guideline';
    verticalRightLine.style.cssText = `
      position: absolute;
      width: 1px;
      height: 200%;
      background: transparent;
      border-left: 1px dashed #FF9800;
      pointer-events: none;
      display: none;
      z-index: 1000;
      top: -50%;
    `;
    
    // 创建刻度信息显示
    const rulerInfo = document.createElement('div');
    rulerInfo.className = 'ruler-info';
    rulerInfo.style.cssText = `
      position: absolute;
      top: 5px;
      right: 5px;
      background: rgba(0, 0, 0, 0.7);
      color: white;
      padding: 4px 8px;
      border-radius: 3px;
      font-size: 12px;
      z-index: 1001;
      pointer-events: none;
      display: none;
    `;
    
    // 将元素添加到容器
    canvasWrapper.appendChild(horizontalLine);
    canvasWrapper.appendChild(horizontalBottomLine);
    canvasWrapper.appendChild(verticalLine);
    canvasWrapper.appendChild(verticalRightLine);
    canvasWrapper.appendChild(rulerInfo);
    
    // 保存引用
    guideLines.value = {
      horizontal: horizontalLine,
      horizontalBottom: horizontalBottomLine,
      vertical: verticalLine,
      verticalRight: verticalRightLine,
      info: rulerInfo
    };
  };

  return {
    canvas: window.globalCanvas, // 直接返回非响应式实例
    canvasRef, // 返回响应式引用用于UI更新
    selectedObject,
    canvasContentWidth,
    canvasContentHeight,
    saved,
    pxPerMm, // 导出响应式的pxPerMm
    initCanvas,
    pxToMm,
    mmToPx,
    updateCanvasSize,
    addObject,
    deleteSelectedObject,
    clearCanvas,
    setBackgroundImage,
    removeBackgroundImage,
    generatePreview,
    updateRulerDimensions,
    handleFieldSelected, // 导出字段选择处理函数
    handleFieldUnselected, // 导出字段取消选择处理函数
    addBarcode, // 导出添加条形码函数
    addText,
    addLine,
    addTable, // 导出添加表格函数
    // 添加辅助线相关方法
    initGuideLines,
    guideLines,
  };
} 